package com.atguigu.xuexiplus.controller;

import com.atguigu.xuexiplus.dto.ChatMessage;
import com.atguigu.xuexiplus.dto.UserDTO;
import com.atguigu.xuexiplus.entity.ChatMessageEntity;
import com.atguigu.xuexiplus.service.ChatMessageService;
import com.atguigu.xuexiplus.service.UserService;
import com.atguigu.xuexiplus.result.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.messaging.simp.annotation.SendToUser;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.security.Principal;
import java.time.LocalDateTime;

@RestController
@RequestMapping("/api/chat")
@CrossOrigin(origins = "*")
public class ChatController {

    @Autowired
    private SimpMessagingTemplate messagingTemplate;
    @Autowired
    private ChatMessageService chatMessageService;
    @Autowired
    private UserService userService;

    /**
     * STOMP 群聊消息入口：/app/chat.send
     * 订阅地址：/topic/chat
     */
    @MessageMapping("/chat.send")
    public void sendToTopic(ChatMessage message, Principal principal) {
        System.out.println("收到群聊消息: " + message);
        System.out.println("当前用户Principal: " + principal);
        
        message.setType("chat");
        message.setSendTime(LocalDateTime.now());
        
        // 如果 fromUserId 为空，尝试从 WebSocket 连接中获取
        if (message.getFromUserId() == null && principal != null) {
            try {
                Long userId = Long.parseLong(principal.getName());
                message.setFromUserId(userId);
                System.out.println("从WebSocket连接获取到群聊用户ID: " + userId);
            } catch (NumberFormatException e) {
                System.out.println("无法从Principal获取群聊用户ID: " + principal.getName());
            }
        }
        
        // 创建群聊消息副本（确保字段正确）
        ChatMessage groupMessage = new ChatMessage();
        groupMessage.setType(message.getType());
        groupMessage.setFromUserId(message.getFromUserId());
        groupMessage.setFromNickname(message.getFromNickname());
        groupMessage.setFromAvatarUrl(message.getFromAvatarUrl());
        groupMessage.setToUserId(null); // 群聊消息 toUserId 为 null
        groupMessage.setContent(message.getContent());
        groupMessage.setSendTime(message.getSendTime());
        
        // 发送给所有订阅 /topic/chat 的用户
        messagingTemplate.convertAndSend("/topic/chat", groupMessage);
        System.out.println("✅ 群聊消息已广播给所有用户");
        
        // 保存到数据库
        if (message.getFromUserId() != null) {
            ChatMessageEntity e = new ChatMessageEntity();
            e.setFromUserId(message.getFromUserId());
            e.setToUserId(null); // 群聊消息 toUserId 为 null
            e.setType("CHAT");
            e.setContent(message.getContent());
            e.setIsRead(0);
            e.setCreatedAt(LocalDateTime.now());
            chatMessageService.saveMessage(e);
            System.out.println("✅ 群聊消息已保存到数据库");
        } else {
            System.out.println("fromUserId 为空，跳过群聊消息数据库保存");
        }
    }

    /**
     * STOMP 私聊消息入口：/app/chat.private
     * 订阅地址：/user/{userId}/queue/messages
     */
    @MessageMapping("/chat.private")
    public void sendPrivate(ChatMessage message, Principal principal) {
        System.out.println("=== 收到私聊消息 ===");
        System.out.println("原始消息: " + message);
        System.out.println("当前用户Principal: " + principal);
        System.out.println("原始 fromUserId: " + message.getFromUserId());
        System.out.println("原始 toUserId: " + message.getToUserId());
        System.out.println("原始 sender: " + message.getSender());
        System.out.println("原始 receiver: " + message.getReceiver());
        
        message.setType("private");
        message.setSendTime(LocalDateTime.now());
        
        // 如果 fromUserId 为空，尝试从 WebSocket 连接中获取
        if (message.getFromUserId() == null && principal != null) {
            try {
                Long userId = Long.parseLong(principal.getName());
                message.setFromUserId(userId);
                System.out.println("⚠️ 从WebSocket连接获取到用户ID: " + userId);
                System.out.println("⚠️ 修改后的 fromUserId: " + message.getFromUserId());
            } catch (NumberFormatException e) {
                System.out.println("无法从Principal获取用户ID: " + principal.getName());
            }
        } else {
            System.out.println("✅ fromUserId 不为空，保持原值: " + message.getFromUserId());
        }
        
        // 🔧 修复：确保 toUserId 不被错误修改
        // 如果 toUserId 等于 fromUserId，说明有问题，需要修复
        if (message.getToUserId() != null && message.getFromUserId() != null 
            && message.getToUserId().equals(message.getFromUserId())) {
            System.out.println("⚠️ 检测到 toUserId 等于 fromUserId，可能存在字段错误");
            System.out.println("⚠️ 原始 toUserId: " + message.getToUserId());
            System.out.println("⚠️ 原始 fromUserId: " + message.getFromUserId());
            
            // 🔧 临时修复：如果 receiver 字段不为空，尝试通过用户名查找正确的用户ID
            if (message.getReceiver() != null && !message.getReceiver().isEmpty()) {
                System.out.println("🔧 尝试通过 receiver 字段修复 toUserId: " + message.getReceiver());
                try {
                    // 通过用户名查找用户ID
                    UserDTO targetUser = userService.findByUsername(message.getReceiver());
                    if (targetUser != null && !targetUser.getId().equals(message.getFromUserId())) {
                        message.setToUserId(targetUser.getId());
                        System.out.println("✅ 修复成功！toUserId 从 " + message.getFromUserId() + " 改为 " + targetUser.getId());
                    } else {
                        System.out.println("❌ 无法找到目标用户或目标用户就是发送者: " + message.getReceiver());
                    }
                } catch (Exception e) {
                    System.out.println("❌ 修复失败: " + e.getMessage());
                }
            } else {
                System.out.println("⚠️ receiver 字段为空，无法修复");
            }
        }
        
        System.out.println("处理后的 fromUserId: " + message.getFromUserId());
        System.out.println("处理后的 toUserId: " + message.getToUserId());
        System.out.println("==================");
        
        // 兼容：如果前端传 sender/receiver（用户名），则不依赖 id 路由
        if (message.getToUserId() == null && message.getReceiver() != null) {
            System.out.println("使用用户名路由私聊消息");
            // 以用户名作为 /user 目的地标识（要求握手时也用 username 作为 userId）
            messagingTemplate.convertAndSendToUser(message.getReceiver(), 
                    "/queue/messages", message);
            if (message.getSender() != null) {
                messagingTemplate.convertAndSendToUser(message.getSender(), 
                        "/queue/messages", message);
            }
            // 不保存到数据库，因为缺少用户ID
            return;
        }
        
        if (message.getToUserId() != null) {
            System.out.println("使用用户ID路由私聊消息");
            System.out.println("发送给接收者ID: " + message.getToUserId());
            System.out.println("发送者ID: " + message.getFromUserId());
            
            // 创建发送给接收者的消息副本（保持原始字段）
            ChatMessage messageToReceiver = new ChatMessage();
            messageToReceiver.setType(message.getType());
            messageToReceiver.setFromUserId(message.getFromUserId());
            messageToReceiver.setFromNickname(message.getFromNickname());
            messageToReceiver.setFromAvatarUrl(message.getFromAvatarUrl());
            messageToReceiver.setToUserId(message.getToUserId());
            messageToReceiver.setContent(message.getContent());
            messageToReceiver.setSendTime(message.getSendTime());
            
            System.out.println("📤 发送给接收者的消息: fromUserId=" + messageToReceiver.getFromUserId() + ", toUserId=" + messageToReceiver.getToUserId());
            
            // 创建发送给发送者的消息副本（回显）
            ChatMessage messageToSender = new ChatMessage();
            messageToSender.setType(message.getType());
            messageToSender.setFromUserId(message.getFromUserId());
            messageToSender.setFromNickname(message.getFromNickname());
            messageToSender.setFromAvatarUrl(message.getFromAvatarUrl());
            messageToSender.setToUserId(message.getFromUserId()); // 🔧 修复：回显消息的toUserId应该是发送者ID
            messageToSender.setContent(message.getContent());
            messageToSender.setSendTime(message.getSendTime());
            
            System.out.println("📤 发送给发送者的消息: fromUserId=" + messageToSender.getFromUserId() + ", toUserId=" + messageToSender.getToUserId());
            
            // 发送给接收者
            messagingTemplate.convertAndSendToUser(String.valueOf(message.getToUserId()), 
                    "/queue/messages", messageToReceiver);
            System.out.println("✅ 消息已发送给接收者: " + message.getToUserId());
            
            // 发送给发送者（回显）
            if (message.getFromUserId() != null) {
                messagingTemplate.convertAndSendToUser(String.valueOf(message.getFromUserId()), 
                        "/queue/messages", messageToSender);
                System.out.println("✅ 消息已回显给发送者: " + message.getFromUserId());
            }
            
            // 只有当 fromUserId 不为空时才保存到数据库
            if (message.getFromUserId() != null) {
                ChatMessageEntity e = new ChatMessageEntity();
                e.setFromUserId(message.getFromUserId());
                e.setToUserId(message.getToUserId());
                e.setType("PRIVATE");
                e.setContent(message.getContent());
                e.setIsRead(0);
                e.setCreatedAt(LocalDateTime.now());
                chatMessageService.saveMessage(e);
                System.out.println("✅ 消息已保存到数据库");
            } else {
                System.out.println("fromUserId 为空，跳过数据库保存");
            }
        } else {
            System.out.println("私聊消息接收者ID为空，无法发送私聊消息。");
        }
    }

    @GetMapping("/test")
    public Result<String> test() {
        return Result.success("Chat service OK");
    }

    @org.springframework.web.bind.annotation.GetMapping("/api/chat/history")
    public Result<java.util.List<ChatMessageEntity>> history(@org.springframework.web.bind.annotation.RequestParam Long fromUserId,
                                                             @org.springframework.web.bind.annotation.RequestParam Long toUserId,
                                                             @org.springframework.web.bind.annotation.RequestParam(defaultValue = "1") int page,
                                                             @org.springframework.web.bind.annotation.RequestParam(defaultValue = "20") int size) {
        return Result.success(chatMessageService.listHistory(fromUserId, toUserId, page, size));
    }
}


